/*
 * @Author: 大白
 * @Date: 2019-12-04 09:48:26
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-09-10 09:35:15
 * @Description: 文件描述
 * @FilePath: \cyf_admin\src\store\modules\login.js
 */
import { recursionRouter, setDefaultRoute } from "@/utils/recursion-router"
import router, { defaultRouter, layouts } from "@/router"
import { getRouterMenu } from "@/config/interface"
import { MessageBox } from 'element-ui';

const state = {
  token: "", // 用户token
  sidebarMenu: [], // 导航菜单
  permissionList: null, //所有路由
  userInfo: null,
}
// store 的计算属性
const getters = {
  userInfo: state => state.userInfo
}
const actions = {
  // 登录
  LOGIN ({ commit }, payload) {
    console.log(payload)
    commit('SET_TOKEN', payload.token.token)
    commit('SET_USERINFO', payload.token)
  },
  // 设置路由
  SET_ROUTER ({ commit, state }) {
    // console.log(state)
    getRouterMenu({ userId: state.userInfo.id }).then(res => {
      let routes = recursionRouter(res.data.children, defaultRouter)
      // console.log(routes)
      let routes2 = defaultRouter
      let MainContainer = layouts.find(v => v.path === '/')
      let children = JSON.parse(JSON.stringify(MainContainer.children))
      children.push(...routes)
      MainContainer.children.push(...routes)
      commit('SET_MENU', children)
      setDefaultRoute([MainContainer])
      let initialRoutes = router.options.routes
      router.addRoutes(layouts)
      commit('SET_PERMISSION', JSON.parse(JSON.stringify([...initialRoutes, ...layouts])))
    })
  },
  // 退出登录
  LOGINOUT ({ commit, state }) {
    MessageBox.confirm('是否退出登录?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let mState = JSON.parse(JSON.stringify(state))
      mState.token = ""
      mState.sidebarMenu = []
      mState.permissionList = null
      mState.userInfo = null
      commit('SET_LOGINOUT', mState)
    }).catch(() => {

    });
  },
  // 登录超时-返回登录页
  LOGIN_TIMEOUT ({ commit, state }) {
    let mState = JSON.parse(JSON.stringify(state))
    mState.token = ""
    mState.sidebarMenu = []
    mState.permissionList = null
    mState.userInfo = null
    commit('SET_LOGINOUT', mState)
  },
}
const mutations = {
  SET_TOKEN (state, payload) {
    state.token = payload
  },
  SET_MENU (state, menu) {
    state.sidebarMenu = menu
  },
  SET_PERMISSION (state, data) {
    state.permissionList = data
  },
  SET_LOGINOUT (state, mState) {
    state.token = mState.token
    state.sidebarMenu = mState.sidebarMenu
    state.permissionList = mState.permissionList
    state.userInfo = mState.userInfo
    location.reload()
  },

  // 设置用户信息
  SET_USERINFO (state, payload) {
    state.userInfo = payload
  },
}
export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}







